#include "adc.h"

__IO uint16_t adc_ordinary_valuetab[10] = {0};

static void adc_gpio_config(void)
{
    gpio_init_type gpio_initstructure;
    gpio_default_para_init(&gpio_initstructure);
    gpio_initstructure.gpio_mode = GPIO_MODE_ANALOG;
    gpio_initstructure.gpio_pins = GPIO_PINS_2;
    gpio_init(GPIOA, &gpio_initstructure);
}

/**
 * @brief  dma2 configuration.
 * @param  none
 * @retval none
 */
static void adc_dma_config(void)
{
    dma_init_type dma_init_struct;

    //   nvic_irq_enable(DMA1_Channel1_IRQn, 0, 0);
    dma_reset(DMA2_CHANNEL5);
    dma_default_para_init(&dma_init_struct);
    dma_init_struct.buffer_size = 10;
    dma_init_struct.direction = DMA_DIR_PERIPHERAL_TO_MEMORY;
    dma_init_struct.memory_base_addr = (uint32_t)adc_ordinary_valuetab;
    dma_init_struct.memory_data_width = DMA_MEMORY_DATA_WIDTH_HALFWORD;
    dma_init_struct.memory_inc_enable = TRUE;
    dma_init_struct.peripheral_base_addr = (uint32_t) & (ADC3->odt);
    dma_init_struct.peripheral_data_width = DMA_PERIPHERAL_DATA_WIDTH_HALFWORD;
    dma_init_struct.peripheral_inc_enable = FALSE;
    dma_init_struct.priority = DMA_PRIORITY_MEDIUM;
    dma_init_struct.loop_mode_enable = TRUE;
    dma_init(DMA2_CHANNEL5, &dma_init_struct);

    //   dma_interrupt_enable(DMA2_CHANNEL5, DMA_FDT_INT, TRUE);
    dma_channel_enable(DMA2_CHANNEL5, TRUE);
}

/**
 * @brief  adc configuration.
 * @param  none
 * @retval none
 */
static void adc_config(void)
{
    adc_base_config_type adc_base_struct;

    /* select combine mode */
    adc_combine_mode_select(ADC_INDEPENDENT_MODE);
    adc_base_default_para_init(&adc_base_struct);
    adc_base_struct.sequence_mode = TRUE;
    adc_base_struct.repeat_mode = TRUE;
    adc_base_struct.data_align = ADC_RIGHT_ALIGNMENT;
    adc_base_struct.ordinary_channel_length = 1;
    adc_base_config(ADC3, &adc_base_struct);
    adc_ordinary_channel_set(ADC3, ADC_CHANNEL_2, 1, ADC_SAMPLETIME_239_5);
    adc_ordinary_conversion_trigger_set(ADC3, ADC3_ORDINARY_TRIG_SOFTWARE, TRUE);
    adc_dma_mode_enable(ADC3, TRUE);

    adc_enable(ADC3, TRUE);
    adc_calibration_init(ADC3);
    while (adc_calibration_init_status_get(ADC3));
    adc_calibration_start(ADC3);
    while (adc_calibration_status_get(ADC3));

}

void ADC_Init(void)
{
    adc_gpio_config();
    adc_dma_config();

    adc_config();
}